import decimal
from apps.coffee import models


def filter_channel_1(queryset, value, coffee_client=False):
    """
    过滤商家
    """
    channel_id_list = []
    if isinstance(value, decimal.Decimal):
        value = int(value)
    if isinstance(value, models.Channel):
        channel_parent = value
    elif isinstance(value, str) and not value.isdigit():
        channel_parent = models.Channel.objects.filter(key=value).first()
    elif isinstance(value, int):
        channel_parent = models.Channel.objects.filter(id=value).first()
    else:
        return queryset
    if channel_parent:
        channel_id_list.append(channel_parent.id)
        for child_level_two in channel_parent.children.all():
            channel_id_list.append(child_level_two.id)
            for child_level_three in child_level_two.children.all():
                channel_id_list.append(child_level_three.id)
    if coffee_client:
        queryset = queryset.filter(coffee_client__channel_id__in=channel_id_list)
    else:
        queryset = queryset.filter(coupon__channel_id__in=channel_id_list)
    return queryset


def filter_channel_2(queryset, value, coffee_client=False):
    if isinstance(value, decimal.Decimal):
        value = int(value)
    channel_id_list = []
    if isinstance(value, models.Channel):
        channel_parent = value
    elif isinstance(value, str) and not value.isdigit():
        channel_parent = models.Channel.objects.filter(key=value).first()
    elif isinstance(value, int):
        channel_parent = models.Channel.objects.filter(id=value).first()
    else:
        return queryset
    if channel_parent:
        channel_id_list.append(channel_parent.id)
        for i in channel_parent.children.all():
            channel_id_list.append(i.id)
    if coffee_client:
        queryset = queryset.filter(coffee_client__channel_id__in=channel_id_list)
    else:
        queryset = queryset.filter(coupon__channel_id__in=channel_id_list)
    return queryset


def filter_channel_3(queryset, value, coffee_client=False):
    if isinstance(value, decimal.Decimal):
        value = int(value)
    if isinstance(value, models.Channel):
        channel_parent = value
    elif isinstance(value, str) and not value.isdigit():
        channel_parent = models.Channel.objects.filter(key=value).first()
    elif isinstance(value, int):
        channel_parent = models.Channel.objects.filter(id=value).first()
    else:
        return queryset
    if coffee_client:
        return queryset.filter(coffee_client__channel_id=channel_parent.id)
    return queryset.filter(coupon__channel_id=channel_parent.id)
